package com.yc.weixin.util;

import net.sf.json.JSONObject;

import com.yc.utils.YcUtils;
import com.yc.weixin.bean.menu.Menu;

/**
 * 菜单工具类
 * @author zy
 *
 */
public class MenuUtil {
	/*
	 * 菜单创建(post)接口地址
	 */
	public final static String MENU_CREATE_URL="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	/**
	 * 菜单查询( get)地址
	 */
	public final static String MENU_GET_URL="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	/**
	 * 菜单删除(get)地址
	 */
	public final static String MENU_DELETE_URL="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	
	/**
	 * 菜单创建
	 * @param menu
	 * @param accessToken
	 * @return
	 * @throws Exception 
	 */
	public static boolean createMenu( Menu menu, String accessToken) throws Exception{
		boolean result=false;
		String url=MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken);
		String jsonMenu=JSONObject.fromObject(menu).toString();
		JSONObject jsonObject=WeiXinCommonUtil.httpsRequest(url, "POST", jsonMenu);
		
		if(  jsonObject!=null ){
			int errorCode=jsonObject.getInt("errcode");
			String errorMsg=jsonObject.getString("errmsg");
			YcUtils.logger.debug("自定义创建菜单状态码"+errorCode);
			if( errorCode==0){
				result=true;
			}else{
				result=false;
				YcUtils.logger.error("创建菜单失败 errorcode:"+errorCode+" "+errorMsg);
			}
		}
		return result;
	}
	/**
	 * 菜单查询
	 * @param accessToken
	 * @return
	 * @throws Exception 
	 */
	public static String getMenu( String accessToken) throws Exception{
		String result=null;
		String url=MENU_GET_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject=WeiXinCommonUtil.httpsRequest(url, "GET", null);
		
		if(  jsonObject!=null ){
			result=jsonObject.toString();
		}
		return result;
	}
	/**
	 * 菜单删除
	 * @param accessToken
	 * @return
	 * @throws Exception 
	 */
	public static boolean deleteMenu( String accessToken) throws Exception{
		boolean result=false;
		String url=MENU_DELETE_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject=WeiXinCommonUtil.httpsRequest(url, "GET", null);
		if(  jsonObject!=null ){
			int errorCode=jsonObject.getInt("errcode");
			String errorMsg=jsonObject.getString("errmsg");
			if( errorCode==0){
				result=true;
			}else{
				result=false;
				YcUtils.logger.error("删除菜单失败 errorcode:"+errorCode+" "+errorMsg);
			}
		}
		return result;
	}
	
}
